#include "StatusBarElement.h"

StatusBarElement::StatusBarElement(TextureManager * textureManager, char * textureName, Vector2D position, Vector2D size, Vector2D * textureVertices, float maxValue)
:MenuElement(textureManager, textureName, position, size, textureVertices)
{
	max = maxValue;
	current = maxValue;
}
StatusBarElement::~StatusBarElement()
{
}
void StatusBarElement::Draw(Vector2D parentPosition)
{
	if(label)
	{
		label->Draw(parentPosition);
	}
	
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	glOrtho(0,100,100,0, -1, 1);
	
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();
	glTranslatef(0, 0, -0.5);
	
	//printf("textureIndex = %d\n", textureIndex);
	if(textureIndex >= 0)
	{
		textureManager->EnableTexture(textureIndex);
		glEnable(GL_TEXTURE_2D);
		glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
		glBlendFunc(GL_ONE, GL_ONE);
		glAlphaFunc( GL_GREATER, 0.01 );
  		glEnable( GL_ALPHA_TEST );
  		glEnable(GL_BLEND);
	}
	
	glColor3f(1,1,1);	
	glBegin(GL_QUADS);
	
	float currentLength = size.x * current/max;
	
	Vector2D vertices[4];
	vertices[0] = parentPosition + position;
	vertices[1] = Vector2D(vertices[0].x + currentLength, vertices[0].y);
	vertices[2] = Vector2D(vertices[1].x, vertices[1].y + size.y);
	vertices[3] = Vector2D(vertices[0].x, vertices[2].y);
	
	Vector2D currentTextureVertices[4];
	currentTextureVertices[0] = textureVertices[0];
	float textureLength = (textureVertices[1].x - textureVertices[0].x) * current/max;
	currentTextureVertices[1] = Vector2D(textureVertices[0].x + textureLength, textureVertices[1].y);
	currentTextureVertices[2] = Vector2D(textureVertices[0].x + textureLength, textureVertices[2].y);
	currentTextureVertices[3] = textureVertices[3];
	
	for(int i = 0; i < 4; i++)
	{
		//printf("drawing element %d at\n\t(%f, %f)\n",i, vertices[i].x, vertices[i].y);
		glTexCoord2f(currentTextureVertices[i].x, currentTextureVertices[i].y);
		glVertex3f(vertices[i].x, vertices[i].y, 1);
	}
	glEnd();
	
	glDisable(GL_TEXTURE_2D);
	glDisable(GL_BLEND);
	glPopMatrix();
	glDisable(GL_TEXTURE_2D);
	glDisable(GL_BLEND);
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
}
void StatusBarElement::SetCurrentValue(float value)
{
	if(value >= 0)
		current = value;
	else 
		current = 0;
}